// 首页内容API服务
// 用于从FastAPI后端获取首页内容数据

// API配置
const API_BASE_URL = 'http://localhost:8001'
const API_TIMEOUT = 30000

/**
 * 处理API错误
 * @param {Error} error - 错误对象
 * @throws {Error} 抛出处理后的错误
 */
const handleApiError = (error) => {
  console.error('API请求错误:', error)
  
  if (error.name === 'AbortError') {
    throw new Error('请求超时，请检查网络连接')
  }
  
  if (error.status) {
    switch (error.status) {
      case 404:
        throw new Error('API接口不存在')
      case 500:
        throw new Error('服务器内部错误')
      default:
        throw new Error(`请求失败: ${error.status}`)
    }
  }
  
  if (error.message.includes('Failed to fetch')) {
    throw new Error('网络连接失败，请检查网络设置')
  }
  
  throw new Error(error.message || '未知错误')
}

/**
 * 获取首页内容数据
 * @param {Object} params - 请求参数
 * @param {string} params.category - 分类，默认为'推荐'
 * @param {number} params.page - 页码，默认为1
 * @param {number} params.pageSize - 每页数量，默认为20
 * @returns {Promise<Object>} 返回包含内容数据的Promise
 */
export const getHomeFeeds = async (params = {}) => {
  try {
    // 构建查询参数
    const queryParams = new URLSearchParams({
      category: params.category || '推荐',
      page: (params.page || 1).toString(),
      page_size: (params.pageSize || 20).toString()
    })
    
    const url = `${API_BASE_URL}/api/home/feeds?${queryParams}`
    
    // 创建AbortController用于请求超时控制
    const controller = new AbortController()
    const timeoutId = setTimeout(() => controller.abort(), API_TIMEOUT)
    
    console.log('发送API请求:', { url, params })
    
    // 发送请求
    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
      signal: controller.signal
    })
    
    // 清除超时定时器
    clearTimeout(timeoutId)
    
    // 检查响应状态
    if (!response.ok) {
      const errorText = await response.text()
      console.error('API响应错误:', {
        status: response.status,
        statusText: response.statusText,
        responseText: errorText
      })
      const error = new Error(`HTTP ${response.status}: ${response.statusText}`)
      error.status = response.status
      throw error
    }
    
    // 解析响应数据
    const data = await response.json()
    console.log('API响应数据:', data)
    
    // FastAPI直接返回标准格式，无需额外处理
    return data
    
  } catch (error) {
    handleApiError(error)
  }
}

/**
 * 获取指定分类的内容
 * @param {string} category - 分类名称
 * @param {Object} params - 其他请求参数
 * @returns {Promise<Object>} 返回包含内容数据的Promise
 */
export const getCategoryFeeds = async (category, params = {}) => {
  try {
    const queryParams = new URLSearchParams({
      page: (params.page || 1).toString(),
      page_size: (params.pageSize || 20).toString()
    })
    
    const url = `${API_BASE_URL}/api/category/${encodeURIComponent(category)}/feeds?${queryParams}`
    
    const controller = new AbortController()
    const timeoutId = setTimeout(() => controller.abort(), API_TIMEOUT)
    
    console.log('发送分类API请求:', { url, category, params })
    
    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
      signal: controller.signal
    })
    
    clearTimeout(timeoutId)
    
    if (!response.ok) {
      const error = new Error(`HTTP ${response.status}`)
      error.status = response.status
      throw error
    }
    
    const data = await response.json()
    console.log('分类API响应数据:', data)
    
    return data
    
  } catch (error) {
    handleApiError(error)
  }
}

/**
 * 搜索内容
 * @param {string} keyword - 搜索关键词
 * @param {Object} params - 其他请求参数
 * @returns {Promise<Object>} 返回搜索结果
 */
export const searchFeeds = async (keyword, params = {}) => {
  try {
    const queryParams = new URLSearchParams({
      keyword: keyword,
      page: (params.page || 1).toString(),
      page_size: (params.pageSize || 20).toString()
    })
    
    const url = `${API_BASE_URL}/api/search?${queryParams}`
    
    const controller = new AbortController()
    const timeoutId = setTimeout(() => controller.abort(), API_TIMEOUT)
    
    console.log('发送搜索API请求:', { url, keyword, params })
    
    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
      signal: controller.signal
    })
    
    clearTimeout(timeoutId)
    
    if (!response.ok) {
      const error = new Error(`HTTP ${response.status}`)
      error.status = response.status
      throw error
    }
    
    const data = await response.json()
    console.log('搜索API响应数据:', data)
    
    return data
    
  } catch (error) {
    handleApiError(error)
  }
}

// 导出默认配置
export default {
  API_BASE_URL,
  API_TIMEOUT,
  getHomeFeeds,
  getCategoryFeeds,
  searchFeeds
}